package com.xckj.cycling.utils

import android.Manifest
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.lifecycleScope
import com.inuker.bluetooth.library.utils.BluetoothUtils
import com.tbruyelle.rxpermissions3.Permission
import com.tbruyelle.rxpermissions3.RxPermissions
import com.xckj.cycling.bluetooth.BluetoothClientManager
import io.reactivex.rxjava3.core.Observer
import io.reactivex.rxjava3.disposables.Disposable
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

object BleUtils {

    fun checkPermissionAndOpenBle(activity: FragmentActivity, callback: (Boolean) -> Unit) {
        try {
            RxPermissions(activity).requestEachCombined(
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.BLUETOOTH_ADMIN,
                Manifest.permission.BLUETOOTH_CONNECT
            ).subscribe(object : Observer<Permission> {
                override fun onSubscribe(d: Disposable) {}
                override fun onNext(permission: Permission) {
                    if (permission.granted) {
                        activity.lifecycleScope.launch {
                            if (BluetoothUtils.isBluetoothEnabled()) {
                                callback.invoke(true)
                                return@launch
                            }
                            withContext(Dispatchers.IO) {
                                // 开启蓝牙
                                BluetoothClientManager.getBluetoothClient().openBluetooth()
                            }
                            callback.invoke(true)
                        }
                    } else {
                        callback.invoke(false)
                    }
                }

                override fun onError(e: Throwable) {
                    callback.invoke(false)
                }

                override fun onComplete() {}
            })
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }
}